<template>
  <div>
    <el-card class="card">
      <el-row :gutter="20">
        <el-col :span="18">
          <el-input
              v-model="searchQuery"
              placeholder="搜索用户名或邮箱"
              prefix-icon="el-icon-search"
              clearable
          />
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="openAddUserDialog">添加用户</el-button>
        </el-col>
      </el-row>
      <el-scrollbar height="700px">
        <el-table
            v-if="users.length > 0"
            :data="filteredUsers"
            border
            style="width: 100vh; margin-top: 20px;"
            row-key="id"
        >
          <el-table-column prop="id" label="用户ID" width="180" />
          <el-table-column prop="username" label="用户名" width="180" />
          <el-table-column prop="email" label="邮箱" width="200" />
          <el-table-column label="注册时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column label="用户类型" width="180">
            <template #default="scope">
              <span v-if="scope.row.is_admin">知识管理员</span>
              <span v-else>普通用户</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button
                  type="danger"
                  size="small"
                  @click="handleDelete(scope.row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-else description="暂无用户数据" style="width: 100vh" />
      </el-scrollbar>

    </el-card>
    <el-dialog
        title="确认删除"
        v-model="deleteDialogVisible"
        width="30%"
    >
      <span>确定要删除该用户吗？</span>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog
        title="添加新用户"
        v-model="addUserDialogVisible"
        width="500px"
    >
      <el-form ref="addUserForm" :model="newUser" :rules="addUserFormRules" label-width="120px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="newUser.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="newUser.email" placeholder="请输入邮箱" type="email" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="newUser.password" placeholder="请输入密码" type="password" />
        </el-form-item>
        <el-form-item label="是否管理员" prop="is_admin">
          <el-switch v-model="newUser.is_admin" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addUserDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitNewUser">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, computed, watch, onMounted} from 'vue';
import {ElMessage} from 'element-plus';
import axios from 'axios';

// 用户列表
const users = ref([]);
// 删除的用户ID
const deleteUserId = ref(0);
// 搜索状态
const searchQuery = ref('');

// 时间格式化函数
function formatDate(timestamp) {
  return new Date(timestamp).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  });
}

// 辅助函数：将字符串转换为小写并处理空值
function toLower(str) {
  return str ? str.toLowerCase() : '';
}

// 计算属性：过滤后的用户列表（不区分大小写）
const filteredUsers = computed(() => {
  const query = toLower(searchQuery.value);
  return users.value.filter((user) => {
    return toLower(user.username).includes(query) || toLower(user.email).includes(query);
  });
});

// 删除用户
const handleDelete = (id) => {
  deleteUserId.value = id;
  deleteDialogVisible.value = true;
};

const confirmDelete = async () => {
  await deleteUser(deleteUserId.value);
  deleteDialogVisible.value = false;
};

// 添加用户对话框状态
const addUserDialogVisible = ref(false);

// 新用户数据
const newUser = ref({
  username: '',
  email: '',
  password: '',
  is_admin: false,
});

// 添加用户表单引用
const addUserForm = ref(null);

// 添加用户表单规则
const addUserFormRules = {
  username: [
    {required: true, message: '用户名必填', trigger: 'blur'},
    {min: 3, message: '用户名至少3个字符', trigger: 'blur'},
  ],
  email: [
    {required: true, message: '邮箱必填', trigger: 'blur'},
    {type: 'email', message: '邮箱格式无效', trigger: 'blur'},
  ],
  password: [
    {required: true, message: '密码必填', trigger: 'blur'},
    {min: 6, message: '密码至少6个字符', trigger: 'blur'},
  ],
};

// 打开添加用户对话框
const openAddUserDialog = () => {
  addUserDialogVisible.value = true;
};

// 提交新用户
const submitNewUser = async () => {
  try {
    await addUserForm.value.validate();
    const response = await axios.post('/register', newUser.value, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`,
      },
    });
    ElMessage.success('用户添加成功！');
    addUserDialogVisible.value = false;
    await getUserList();
  } catch (error) {
    if (error.response && error.response.status === 400) {
      ElMessage.error(error.response.data.detail);
    } else {
      ElMessage.error('添加用户时发生错误。');
    }
  }
};

// 重置新用户数据
const resetNewUser = () => {
  newUser.value = {
    username: '',
    email: '',
    password: '',
    is_admin: false,
  };
};

// 监听对话框关闭，重置表单
watch(addUserDialogVisible, (newVal) => {
  if (!newVal) {
    resetNewUser();
  }
});

// 获取所有用户列表
const getUserList = async () => {
  try {
    const {data} = await axios.get('/users/userList', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`,
      },
    });
    users.value = data.data;
    console.log(users.value);
  } catch (e) {
    console.log(e);
  }
};

// 删除用户
const deleteUser = async (user_id) => {
  try {
    const { data } = await axios.delete(`/users/delete/${user_id}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`,
      },
    });
    await getUserList();
    ElMessage({
      message: data.message,
      type: 'warning',
    });
  } catch (e) {
    console.log(e);
  }
};

// 删除对话框状态
const deleteDialogVisible = ref(false);

onMounted(async () => {
  await getUserList();
});
</script>

<style scoped>
.card {
  padding-top: 2%;
  width: 100%;
  height: 100%;
}
</style>